package com.gateway.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MyGlogbalFilter
 * @Description
 * @Author xiaoxi
 * @Date 2022/11/17 0:00
 * @Version 1.0
 */
@Component
public class MyGlobalFilter implements GlobalFilter {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        ServerHttpRequest request = exchange.getRequest();

        System.out.println("你好呀~~~~~~~~~~~~~~~~~~~~~~~~~: " + request.getURI());

        if (request.getURI().toString().contains("order")) {
            return chain.filter(exchange);
        } else {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            Map<String,String> map = new HashMap<>();
            map.put("status", "-1");
            map.put("data", "鉴权失败");
            DataBuffer buffer = null;
            try {
                buffer = response.bufferFactory().wrap(objectMapper.writeValueAsString(map).getBytes(StandardCharsets.UTF_8));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } finally {
                return response.writeWith(Mono.just(buffer));
            }

        }


    }

}
